package com.wuyou.securitydemo.utils;

import cn.hutool.core.util.StrUtil;
import com.wuyou.sso.common.contant.AuthConstants;
import com.wuyou.securitydemo.userdetails.CustomizedUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 安全工具类
 *
 * @author lishangbu
 */
@UtilityClass
public class SecurityUtils {

    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     *
     * @param authentication
     * @return <p>
     */
    public CustomizedUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof CustomizedUser) {
            return (CustomizedUser) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public CustomizedUser getUser() {
        Authentication authentication = getAuthentication();
        return authentication == null ? null : getUser(authentication);
    }

    /**
     * 获取用户角色信息
     *
     * @return 角色集合
     */
    public List<Long> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<Long> roleIds = new ArrayList<>();
        authorities.stream()
                .filter(granted -> StrUtil.startWith(granted.getAuthority(), AuthConstants.ROLE))
                .forEach(
                        granted -> {
                            String id = StrUtil.removePrefix(granted.getAuthority(), AuthConstants.ROLE);
                            roleIds.add(Long.parseLong(id));
                        });
        return roleIds;
    }
}
